import Request from '../lib/Request'
import storage from '../util/storage'
import config from './config.js'
import util from './util'
import store from '../vuex/store.js'
import { promisify, log } from './helper.js'
// storage.getRepository('global').getItem()

const http = new Request({
	baseUrl: config.mengxiaoer.BASE_URL,
})

http.interceptors.request.use((requestConfig) => {
	// console.log(requestConfig)
	let loginfo = storage.getRepository('global').getItemSync('loginInfo');
	// 拦截请求的数据, 可做公共参数添加
	requestConfig.header = { 
		'Content-Type': "application/json;charset=utf-8"
	}
	
	requestConfig.data.token = loginfo.token;
	requestConfig.data.sid = loginfo.sid;
	// console.log(requestConfig)
	//是否加密
	if(config.mengxiaoer.IS_ENCRYPT && requestConfig.method !== 'GET' ) {
	    requestConfig.data = util.toRc4(JSON.stringify(requestConfig.data))
		// requestConfig.data = JSON.stringify(requestConfig.data)
	}
	return requestConfig
})

http.interceptors.response.use(async (result) => {
	log.reportRequest(result)
	// console.log(result)
	let requestData = JSON.parse(util.decRc4(result.data))
	// let requestData = result.data;
	// console.log(requestData)
	// 拦截返回的数据, 可做状态判断, 网络状态为200, 304等
	if(requestData.code == 0) {
		return Promise.resolve(requestData)
	}else if(requestData.code == 422){//如果登录状态失效，则返回登录界面并清空缓存
		// alert(requestData.msg)
		
		uni.showModal({
			title:'提示',
			content: requestData.msg,
			complete:function(){
				store.dispatch("global/exitLogin")
			}
		})
		return Promise.reject({status: requestData.code, msg: requestData.msg})
	}else if(requestData.code == 401){//如果是后台返回的错误
		return Promise.reject(requestData)
	}else {
		// alert(requestData.msg)
		uni.showToast({
		  title: requestData.msg,
		  icon: 'none'
		})
		return Promise.reject(requestData)
	}
	
} , (err) => {
  if (err.response) {
    // 网络出现500 或 400
    if (/^50[0-9]/.test(err.response.statusCode)) {
      // 服务器错误
      uni.showToast({
        title: `服务器错误 [${err.response.statusCode}]`,
        icon: 'none'
      })
    } else if (/^4[0-1][0-9]/.test(err.response.statusCode)) {
      // 本地请求错误
      uni.showToast({
        title: `请求出错 [${err.response.statusCode}]`,
        icon: 'none'
      })
    }
    return Promise.reject(err.response)
  } else {
    // wx.request fail 错误
    uni.showToast({
      title: '请求超时 [' + err.errMsg + ']',
      icon: 'none'
    })
    return Promise.reject({...err, timeout: true})
  }
})

export default http